import getopt
import json
import threading
from datetime import date
from fileUtil import getFilePathList, analizeFileIsUpload
import os
import sys
from xmlutil import anlizexml
import requests

from dbmanager.sqllite import SqliteSession, DBXmlUpload
from pikautil.AsyncMqPublish import MqPublisher
from config import config, loadConfig
from processutil.ProcessDBStore import ProcessDBStore
import logging.config

# log文件夹
if os.path.exists('./logs') is False:
    os.makedirs('./logs')

# 日志配置
with open('./conf/logging.json', 'rt') as f:
    logConfig = json.load(f)
logging.config.dictConfig(logConfig)
logger = logging.getLogger(__name__)


def equipmentSchedule(rootpath, rabbitmq):
    result = []
    logger.info("equipmentSchedule inner")
    # now = date.today()
    now = date(2018,3,26)
    path = getFilePathList(rootpath, now)
    filelist = analizeFileIsUpload(now, path)
    filelist=list(filelist)
    for file in filelist:
        result += anlizexml(file)
    if len(result)>0:
        rabbitmq.publasher(json.dumps(result), callback=macallback,filelist=filelist, date=now)
    equthread = threading.Timer(config.get('schedule').get('synchronize'), equipmentSchedule,
                                args=(rootpath, rabbitmq))

    equthread.start()


def macallback(message, *args, **kwargs):
    logger.info("mq delevery successful,message={}",message)
    filelist = json.dumps(kwargs.get('filelist'))
    now = kwargs.get('date')
    session = SqliteSession()
    xmlupload = DBXmlUpload(filelist=filelist, date=now)
    session.add(xmlupload)
    logger.info("those xml has been publisher:{}", filelist.__str__())
    session.commit()


def heartSchedule(url):
    try:
        requests.get(url, timeout=10)
    except requests.exceptions.ConnectionError as e:
        logger.error("heart timeout")
    finally:
        heartthread = threading.Timer(config.get('schedule').get('heart'), heartSchedule,
                                      args=(url,))
        heartthread.start()


def getHeartUrl():
    name = config.get('device').get("name")
    code = config.get('device').get("code")
    baseurl = config.get('ScaDA').get('baseurl')
    hearturl = config.get('ScaDA').get('hearturl')
    hearturl = baseurl + hearturl % (name, code)
    return hearturl


def getprocessUrl():
    name = config.get('device').get("name")
    code = config.get('device').get("code")
    baseurl = config.get('ScaDA').get('baseurl')
    processurl = config.get('ScaDA').get('processurl')
    processurl = baseurl + processurl % (name, code)
    return processurl


def processSChedule(process):
    process.scheduled()
    processthread = threading.Timer(config.get('schedule').get('processtime'), processSChedule, args=(process,))
    processthread.start()


def main():
    processurl = getprocessUrl()
    process = ProcessDBStore(config.get("process").get("name"), config.get("process").get("isreport"),
                             url=processurl)
    rabbitmq = MqPublisher(config.get("MQ")['url'], config.get("MQ")['exchange'], config.get("MQ")['exchange_type'],
                           config.get("MQ")['routing_key'],
                           config.get("MQ")['queuename'])
    rabbitmq.connect()
    equipmentSchedule(config.get("xmlupload").get("rootpath"), rabbitmq)
    processSChedule(process)
    hearturl = getHeartUrl()
    heartSchedule(hearturl)
    return rabbitmq


if __name__ == '__main__':
    options, args = getopt.getopt(sys.argv[1:], "f:", ["file="])
    if len(options) == 0:
        print("请配置文件路径")
    for o, a in options:
        if o in ("-f", "--file"):
            if a and os.path.exists(a):
                config = loadConfig(a)
            else:
                print("文件路径有误")
                sys.exit()
    rabbitmq = None
    try:
        if config:
            rabbitmq = main()
    except KeyboardInterrupt:
        if rabbitmq:
            rabbitmq.close()
